package pl.edu.agh.gronoMining.owlToGraphConverter.parser.implementation;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import pl.edu.agh.gronoMining.owlToGraphConverter.graph.Edge;
import pl.edu.agh.gronoMining.owlToGraphConverter.graph.Graph;
import pl.edu.agh.gronoMining.owlToGraphConverter.graph.Vertex;
import pl.edu.agh.gronoMining.owlToGraphConverter.parser.ISimpleSerializer;

public class ToOneGraphSerializer implements ISimpleSerializer {
	
	private static Logger logger = Logger.getLogger(SimpleSerializer1.class);

	public void serialize(Graph[] graphs, OutputStream out) throws IOException {
		
		logger.info("Start serializing graph "+0);
		
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
		
		writer.write("t # " + 0 +"\n");
		
		int nodeId = 0;
		Map <Integer, Integer> numberToIdMap = new HashMap<Integer, Integer>();
		Set<SimpleEdge> edgesSet = new HashSet<SimpleEdge>();
		
		for (Graph g : graphs) {
			
			for (Vertex v : g.vertexSet()) {
				writer.write("v "+nodeId+" "+v.getType()+":"+v.getLabel()+"\n");
				numberToIdMap.put(v.getNumber(), nodeId);
				nodeId++;
			}
			
			for (Edge e : g.edgeSet()) {
				int id1 = numberToIdMap.get(e.getV1().getNumber());
				int id2 = numberToIdMap.get(e.getV2().getNumber());
				edgesSet.add(new SimpleEdge(id1, id2, 1));
			}
			
		}
		
		for (SimpleEdge e : edgesSet) {
			writer.write("e "+e.getId1()+" "+e.getId2()+" "+e.getLabel()+"\n");
		}
		
		writer.flush();
		
		logger.info("end serializing");
		
	}
	
}

class SimpleEdge {
	
	private int id1, id2, label;
	
	public SimpleEdge(int id1, int id2, int label) {
		this.id1 = id1;
		this.id2 = id2;
		this.label = label;
	}
	
	public int getId1() {
		return this.id1;
	}
	
	public int getId2() {
		return this.id2;
	}
	
	public int getLabel() {
		return label;
	}
}
